package com.zzw.system.controller;

import com.zzw.common.result.Result;
import com.zzw.common.utils.JwtHelper;
import com.zzw.vo.system.LoginVo;
import com.zzw.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author zzw
 * @date 2023/4/19 15:11
 */
@Api(tags = "后台登录管理")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    UserDetailsService userDetailsService;

    /**
     * 登录
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo) {
////        根据用户名获取用户
//        SysUser sysUser=sysUserService.getByUserName(loginVo.getUsername());
////        判断是否为空
//        if(sysUser==null) {
//            throw new zzwException(ACCOUNT_ERROR.getCode(),ACCOUNT_ERROR.getMessage());
//        }
////        判断md5加密后的密码是否正确
//        if(!MD5.encrypt(loginVo.getPassword()).equals(sysUser.getPassword())) {
//            throw new zzwException(PASSWORD_ERROR.getCode(), PASSWORD_ERROR.getMessage());
//        }
////        判断状态是否可用
//        if(sysUser.getStatus() ==0){
//            throw  new zzwException(ACCOUNT_STOP.getCode(), ACCOUNT_STOP.getMessage());
//        }
////        生成JwtToken
//        Map<String,Object> map = new HashMap<>();
//        String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());
//        map.put("token",token);

        userDetailsService.loadUserByUsername(loginVo.getUsername());

        return Result.ok();
    }
    /**
     * 获取用户信息
     * @return
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public Result info(HttpServletRequest request) {
//        JwtToken在前端设置在请求头，支持跨域（cookie不支持跨域）
//        获取请求头token字符串
        String token = request.getHeader("token");
//        解析token获取用户名（id）
        String username = JwtHelper.getUsername(token);
//        根据用户名获取用户（基本信息，菜单权限，按钮权限等）
        Map<String, Object> map = sysUserService.getUserInfo(username);
        return Result.ok(map);
    }
    /**
     * 退出
     * @return
     */
    @ApiOperation("退出")
    @PostMapping("/logout")
    public Result logout(){
        return Result.ok();
    }

}